package at.catalysts.imgClassifier.dataFinders;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Collection;
import java.util.Collections;

import javax.imageio.ImageIO;

import org.apache.log4j.Logger;

import at.jaki.ubb.crawling.api.DataFinder;
import at.jaki.ubb.crawling.model.DataFinderResult;
import at.jaki.ubb.crawling.model.Target;

public class ImgReader implements DataFinder<String, String, String> {

	public static final String TYPE_IMG_URL = "imgUrl";
	public static final String TYPE_IMG_RES = "imgRes";

	private static final Logger LOG = Logger.getLogger(ImgReader.class);

	public DataFinderResult<String, String> findData(Target<String> t) {

		LOG.info("getting page: " + t.getValue());

		getImg(t.getValue());

		return null;
	}

	private String getImg(String value) {
		BufferedImage image = null;
		try {
			URL url = new URL(value);
			String fileName = url.toString().replaceAll("\\W+", "_");
			image = ImageIO.read(url);

			// for png
			ImageIO.write(image, "png", new File("img/" + fileName + ".png"));

		} catch (IOException e) {
			LOG.warn(e.getClass()+" "+e.getMessage());
			e.printStackTrace();
		}
		return "";
	}

	public void init() {

	}

	public Collection<String> getTypes() {
		return Collections.singletonList(TYPE_IMG_URL);
	}
}
